from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import login
from django.http import JsonResponse, HttpResponseServerError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE
from utils.secret import SecretOauth


def is_bind_openid(request,openid):
    # 如果绑定了
    try:
        oauth_user = OAuthQQUser.objects.get(openid=openid)


    except Exception as e:
        logger.error(e)
        # 如果openid没绑定美多商城用户
        openid = SecretOauth().dumps(openid)
        print(type(openid))
        print(openid)
        context = {
            'openid': openid
        }
        return render(request, 'oauth_callback.html', context)
    else:
        # 绑定了-保持登录状态->重定向到首页-->设置cookie username
        qq_user = oauth_user.user
        login(request, qq_user)

        # 响应结果
        response = redirect(reverse('contents:index'))

        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)

        return response

# 测试页面显示
# class HelloView(View):
#     def get(self,request):
#         return render(request,'oauth_callback.html')


# 1. 获取qq登陆的url
class QQAuthURLView(View):
    """提供QQ登录页面网址
       https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
       """
    def get(self,request):

        # 获取QQ登陆页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state='')
        login_url = oauth.get_qq_url()

        return JsonResponse({'code': RETCODE.OK,
                             'errmsg': 'OK',
                             'login_url':login_url})

# 2. 回调网址 code-->token-->openid
class QQAuthUserView(View):
    """用户扫码登录的回调处理"""

    def get(self, request):
        """Oauth2.0认证"""

        # 接收Authorization Code
        code = request.GET.get('code')

        # if not code:
        #     return HttpResponseForbidden('缺少code')
        # 创建对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state='')
        try:
            # 使用code向QQ服务器请求access_token
            token = oauth.get_access_token(code)

            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(token)
            print(type(openid))
            print(openid)
        except Exception as e:
            logger.error(e)
            return HttpResponseServerError('OAuth2.0认证失败')

        # 判断openid是否绑定用户
        response = is_bind_openid(request,openid)
        return response

    # 绑定openid
    def post(self, request):
        # 1.接收参数 form POST
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code = request.POST.get('sms_code')
        openid = request.POST.get('openid')

        # 2.校验--判空--正则--短信验证码

        # 3.解密--openid 校验
        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})

        # 4.判断用户是否存在 存在 user; 不存在新建user
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 不存在 新建user
            user = User.objects.create(username=mobile, password=pwd, mobile=mobile)
        else:
            # 密码不正确
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 5.user绑定openid
        try:
            # 解密openid
            print(openid)
            openid = SecretOauth().loads(openid)
            print(openid)
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})

        # 6. 保持登录状态--重定向首页--set_cookie username
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=24 * 15 * 3600)
        return response


